package designpatterns.prototype;

import java.io.*;

/**
 * 原型模式  利用克隆生成新对象（深克隆）
 * 原型对象内联的对象，需要实现Serializable,否则无法序列化
 *
 * @author miweidong
 * @date 2021-09-16 15:39
 */
public class Prototype {

    @Override
    public Prototype clone() {
        Prototype prototype = null;
        try (
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
            objectOutputStream.writeObject(this);
            prototype = (Prototype) objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return prototype;
    }
}
